<?php


namespace app\web\controller;

use app\common\lib\Aes;
use app\common\lib\exception\ApiException;
use app\common\model\ZhunleCourseSectionExercise;
use think\Controller;

class SectionExercise extends Controller
{
    public function index(string $token)
    {
        $isEncode = input('is_encode/d', 0);
        if (!$isEncode)
        {
            //注意token中不能存在空格，因为php的urldecode方法会把“+”替换成空格
            $token = urldecode($token);
            //把空格替换成“+”
            $token = str_replace(' ', '+', $token);
        } elseif ($isEncode === 2)
        {
            $token = base64_decode($token, true);
        }
        $Aes = new Aes();
        // 解密
        $aesParams = $Aes->decryptWithOpenssl($token);
        // 将解密后的数据转换成数组
        $params = $Aes->strDataToArray($aesParams);
        if (!isset($params['csid']))
        {
            return "<h1>加载失败,请稍后重试！</h1>";
        }
        // 获取章节练习数据
        $sectionExerciseData = (new ZhunleCourseSectionExercise())->getSectionExercise($params['csid']);

        $sectionExerciseData = json_decode($sectionExerciseData, true);
        if (!empty($sectionExerciseData))
        {
            // 初始化 定义完整的习题
            $temp = [];
            foreach ($sectionExerciseData as $item)
            {
                if ($item['title'] && $item['optionA'] && $item['optionB'] && $item['optionC'] && $item['optionD'] && $item['answer'] && $item['analysis'])
                {
                    $temp[] = $item;
                }
            }
            // 习题数据重新赋值
            $sectionExerciseData = $temp;
            if ($sectionExerciseData)
            {
                $is_have_exercise = 1;
            } else
            {
                $is_have_exercise = 0;
            }
        } else
        {
            $is_have_exercise = 0;
        }

        if ($is_have_exercise == 0)
        {
            throw new ApiException('当前课程暂无习题');
        }

        $this->assign('sectionExerciseData', json_encode($sectionExerciseData));
        $this->assign('appType', $params['app-type'] ?? 'web');
        $this->assign('callbackUrl', $params['callback_url'] ?? 'web');

        return $this->fetch();
    }
}
